package com.jiniutech.common.log;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class LogAspect {
    private ThreadLocal<Long> time = new ThreadLocal<>();

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    private void logGet() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    private void logPost() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PutMapping)")
    private void logPut() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
    private void logDelete() {
    }


    @Before("logGet()||logPost()||logPut()||logDelete()")
    public void before(JoinPoint joinPoint) {
        time.set(System.currentTimeMillis());
    }


    @AfterReturning(returning = "result", pointcut = "logGet()||logPost()||logPut()||logDelete()")
    public void logGetAfterReturning(JoinPoint joinPoint, Object result) {
        doLog(joinPoint, result);
    }

    private void doLog(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + "()";
        String args = JSON.toJSONString(joinPoint.getArgs());
        long periodTime = System.currentTimeMillis() - time.get();
        log.info("method:" + methodName + ", " +
                "params:" + args + ", " +
                "time:" + periodTime + "ms, " +
                "response body:" + JSON.toJSONString(result) + ".");
    }
}
